<template>
  <div class="page-warp">
    <div style="padding-bottom: 12px">
      <el-select @change="handleMacSelected" v-model="currentMid" placeholder="请选择" style="margin-right: 12px; width: 220px">
        <el-option v-for="item in macList" :key="item.mid" :label="item.label + '(' + item.mid + ')'" :value="item.mid"> </el-option>
      </el-select>
      <el-button @click="handlePush" type="primary">下发到主控板</el-button>
      <el-button @click="handlePull($event, false)" type="success">仅读取配置</el-button>
      <el-button @click="handlePull($event, true)" type="primary">读取并覆盖当前配置</el-button>
    </div>
    <div class="edit-form">
      <div style="width: 300px; padding: 0 10px 10px 0" v-for="item in fieldProp" :key="item.prop">
        <div>
          <div v-if="item.opts" class="select-x-wrap" style="width: 290px; display: flex; align-items: center">
            <div class="select-x-prepend" :style="configSaved[item.prop] == configApplied[item.prop] ? 'color:#777' : 'color:red'" slot="prefix">
              {{ item.label }}
            </div>
            <el-select v-model="configSaved[item.prop]" placeholder="请选择">
              <el-option v-for="opt in item.opts" :key="opt" :label="opt" :value="opt"> </el-option>
            </el-select>
          </div>
          <el-input v-else v-model="configSaved[item.prop]">
            <template slot="prepend">
              <span class="item-label" :style="configSaved[item.prop] == configApplied[item.prop] ? 'color:#777' : 'color:red'">{{
                item.label
              }}</span>
            </template>
            <template v-if="item.unit" slot="append">{{ item.unit }}</template>
          </el-input>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import BlockTitle from '@/components/BlockTitle/index.vue'
// import { configSaved, fieldProp } from './config'
import { MqttHelper } from '@/utils/mqttHelper'
// import { configSaved } from './config'
var M = new MqttHelper()
var resolveProxy = null

export default {
  name: 'BdConfig',
  components: { BlockTitle },
  data() {
    return {
      currentMid: '0000000000000000',
      macList: [
        { label: '机台2', mid: '1234567890ABCDEF' },
        { label: '机台1', mid: '0000000000000000' },
      ],
      configSaved: {},
      configApplied: {},
      fieldProp: [],
      saved: true,
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.getFieldProp()

    this.$EVBUS.$on('rep-get-base-cfg', (data) => {
      resolveProxy(data.Param)
    })

    this.$EVBUS.$on('rep-set-base-cfg', (data) => {
      resolveProxy(data.Result)
    })
  },
  methods: {
    handleMacSelected() {
      this.getSaved()
    },
    handleClick(e) {
      console.log('handleClick', e)
    },
    async getFieldProp() {
      this.$ShowLoading()
      try {
        const res = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: "select * from z_doc where dkey = 'baseConfig'", pagenum: 1, pagesize: 10 },
        })

        this.fieldProp = JSON.parse(res.obj.list[0].dvalue)
        this.getSaved()
      } catch (e) {
        console.log('Error:', e)
      } finally {
        this.$CloseLoading()
      }
    },

    async getSaved() {
      const resConfigSaved = await request({
        url: '/db/getData',
        method: 'post',
        data: { sql: `select * from z_doc where dkey = '${this.currentMid}'`, pagenum: 1, pagesize: 10 },
      })

      if (resConfigSaved.obj.list.length > 0) {
        this.saved = true
        this.configSaved = JSON.parse(resConfigSaved.obj.list[0].dvalue)
      } else {
        this.saved = false
        this.configSaved = {}
      }
      this.handlePull(null, false)
    },

    async handlePush() {
      try {
        this.$ShowLoading()
        this.configSaved = M.modelRebuild(this.configSaved, 'SetBaseCfg')
        const payload = {
          id: this.currentMid,
          PackType: 'SetBaseCfg',
          TimeSec: this.$dayjs().unix(),
          Param: this.configSaved,
        }

        // console.log(JSON.stringify(payload))
        const res = await M.doPublish({
          topic: `WxProject/spindle/${this.currentMid}/datadown`,
          qos: 1,
          payload: JSON.stringify(payload),
        })

        const relayRes = await new Promise((resolve, reject) => {
          resolveProxy = resolve
        })
        // console.log('bdConfig.vue > handlePush', relayRes)

        await this.syncToDb()
        this.configApplied = { ...this.configSaved }
      } catch (e) {
        console.log(e)
      } finally {
        this.$CloseLoading()
      }
    },

    async handlePull(_, reset) {
      try {
        this.$ShowLoading()
        const payload = {
          id: this.currentMid,
          PackType: 'GetBaseCfg',
          TimeSec: this.$dayjs().unix(),
        }
        // console.log(JSON.stringify(payload))
        await M.doPublish({
          topic: `WxProject/spindle/${this.currentMid}/datadown`,
          qos: 1,
          payload: JSON.stringify(payload),
        })

        const relayRes = await new Promise((resolve, reject) => {
          resolveProxy = resolve
        })
        // console.log('bdConfig.vue > handlePull', relayRes)
        this.configApplied = relayRes
        if (reset) this.configSaved = { ...relayRes }
      } catch (e) {
        console.log(e)
      } finally {
        this.$CloseLoading()
      }
    },

    async syncToDb() {
      const res = await request({
        url: '/lowcode/commonUpdate',
        method: 'post',
        data: [
          {
            tableName: 'z_doc',
            action: this.saved ? 'update' : 'insert',
            dataList: [{ dkey: this.currentMid, dvalue: JSON.stringify(this.configSaved) }],
          },
        ],
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';
.page-warp {
  padding: 10px 20px;
  box-sizing: border-box;
}
.edit-form {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}
::v-deep .el-input-group__prepend {
  width: 137px;
}
::v-deep .el-input-group__append {
  width: 62px;
}
.select-x-wrap {
  line-height: normal;
  display: inline-table;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 12px;
}
.select-x-prepend {
  border-right: 0;
  height: 28px;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  background-color: #f5f7fa;
  color: #909399;
  vertical-align: middle;
  display: table-cell;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 20px;
  width: 1px;
  white-space: nowrap;
  line-height: normal;
  display: flex;
  align-items: center;
  width: 156px;
  border-collapse: separate;
  border-spacing: 0;
}
.item-label {
  width: 156px;
}
</style>
